﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ContactDetailControl : RSBaseUserControl
    {

        
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["action"] == "add")
                {
                    SetAddNewAction();
                }
            }
        }
        private void SetAddNewAction()
        {
            btnEditContact.Visible = false;
            btnSaveContact.Visible = true;
            btnDeleteContact.Visible = false;
            //SetControlEnabledState(true);
        }
        public void SetControlEnabledState(bool bstate = false)
        {
            
            RSSBMCommonFunctions.SetControlsEnabledState(this, bstate);
        }
        protected void btnEditContact_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                SetControlEnabledState(true);
                btnEditContact.Visible = false;
                btnSaveContact.Visible = true;
                btnDeleteContact.Visible = true;
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string prevurl = string.Empty;
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();

            Response.Redirect(prevurl);
        }
        protected void btnDeleteContact_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int companyid = userIdentity.RSCompanyId;
                int contactid = txtContactId.Text == "" ? 0 : Convert.ToInt32(txtContactId.Text);

                if (companyid > 0 && contactid > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@contactid", SqlDbType.Int, 0, ParameterDirection.Input, contactid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblContact WHERE ContactId=@contactid AND CompanyId=@companyid");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    ucModalActionMessageControl.ShowModal("Contact Deleted Successfully!", "RSViewContacts.aspx", true);
                }
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
        protected void btnSaveContact_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;
            int BillingLocationId = ddlBillingLocationId.SelectedValue == "0" ? 0 : Convert.ToInt32(ddlBillingLocationId.SelectedValue);
            int ContactId = txtContactId.Text == "" ? 0 : Convert.ToInt32(txtContactId.Text);
            string FirstName = txtFirstName.Text.Trim();
            string MiddleName = txtMiddleName.Text.Trim();
            string LastName = txtLastName.Text.Trim();
            string Phone = txtPhone.Text.Trim();
            string Mobile = txtMobile.Text.Trim();
            string Fax = txtFax.Text.Trim();
            string Email = txtEmail.Text.Trim();
            string Title = txtTitle.Text.Trim();
            string Note = txtContactNote.Text.Trim();
            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@FirstName", SqlDbType.NVarChar, 25, ParameterDirection.Input, FirstName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@MiddleName", SqlDbType.NVarChar, 25, ParameterDirection.Input, MiddleName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LastName", SqlDbType.NVarChar, 25, ParameterDirection.Input, LastName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Phone", SqlDbType.NVarChar, 15, ParameterDirection.Input, Phone);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Mobile", SqlDbType.NVarChar, 15, ParameterDirection.Input, Mobile);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Fax", SqlDbType.NVarChar, 15, ParameterDirection.Input, Fax);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Email", SqlDbType.NVarChar, 50, ParameterDirection.Input, Email);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Title", SqlDbType.NVarChar, 25, ParameterDirection.Input, Title);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Note", SqlDbType.NVarChar, -1, ParameterDirection.Input, Note);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Active", SqlDbType.Bit, 0, ParameterDirection.Input, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@BillingLocationId", SqlDbType.Int, 0, ParameterDirection.Input, BillingLocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ContactId", SqlDbType.Int, 0, ParameterDirection.Input, ContactId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveContact");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);

            string prevurl = string.Empty;
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();
            ucModalActionMessageControl.ShowModal("Contact Successfully Saved!", prevurl, true);
        }


        public bool LoadContactData(int companyid, int contactid)
        {
            bool bHasValue = false;
            LoadContactBillingLocationID(companyid, contactid);

            String strSQL = "select FirstName,MiddleName,LastName,BillingLocationId,Phone,Mobile,Fax,Email,Title,Note,CompanyId,Active from rs_tblContact where contactid=@contactid and companyid=@companyid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@contactid";
            param.Value = contactid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if(myDataReader.HasRows)
            {
                myDataReader.Read();
                txtContactId.Text = contactid.ToString();
                txtFirstName.Text = myDataReader["FirstName"].ToString();
                txtMiddleName.Text = myDataReader["MiddleName"].ToString();
                txtLastName.Text = myDataReader["LastName"].ToString();
                txtPhone.Text = myDataReader["Phone"].ToString();
                txtMobile.Text = myDataReader["Mobile"].ToString();
                txtFax.Text = myDataReader["Fax"].ToString();
                txtEmail.Text = myDataReader["Email"].ToString();
                txtTitle.Text = myDataReader["Title"].ToString();
                txtContactNote.Text = myDataReader["Note"].ToString();

                if (myDataReader["BillingLocationID"] != DBNull.Value)
                    ddlBillingLocationId.SelectedValue = myDataReader["BillingLocationID"].ToString();

                SetControlEnabledState(false);
                btnEditContact.Enabled = true;
                bHasValue = true;

            }

            myConnection.Close();
            return bHasValue;
        }

        private void LoadContactBillingLocationID(int companyid, int contactid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "SELECT LocationID FROM [rs_tblContactLocation] WHERE ContactID=@ContactID AND CompanyID=@CompanyID ORDER BY LocationID";
            SqlParameter param;
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@contactid";
            param.Value = contactid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlBillingLocationId.Items.Clear();
            ddlBillingLocationId.DataSource = myDataReader;
            ddlBillingLocationId.DataTextField = "LocationID";
            ddlBillingLocationId.DataValueField = "LocationID";
            ddlBillingLocationId.DataBind();
            ddlBillingLocationId.Items.Insert(0, new ListItem("< Please select >", "0"));
            myConnection.Close();
        }

    }
}